package org.fujene.diskblock;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.fujene.memoryblock.MemoryBlock;
import org.fujene.memoryblock.PureContentBlock;
import org.fujene.structure.Constants;
import org.fujene.toolbox.ByteConverter;

public class PureContentDiskBlock extends DiskBlock {
	public PureContentDiskBlock(File fileDesc) throws Exception {
		super(fileDesc);
	}
	
	public PureContentDiskBlock(PureContentBlock memBlock, String dir) {
		super(memBlock, dir);
	}
	
	public PureContentDiskBlock(int ID, File desc, int defaultBodySize,
			int defaultOptionSize) throws Exception {
		super(ID, desc, Constants.MEMORY_TYPE_PURECONTENT, defaultBodySize,
				defaultOptionSize);
	}
	
	public String getContent(int ptr) throws IOException{
		if(ptr >= bodySize)
			return null;
		FileInputStream stream = null;
		byte[] val = new byte[STRLEN];
		int strlen;

		try {
			stream = new FileInputStream(fileDesc);
			switch (version) {
			case Constants.FINALVER:
				stream.skip((4 * HEADERLEN) + (4 * optionSize) + ptr);
				stream.read(val);
				strlen = ByteConverter.byteToInt(val);
				
				val = new byte[strlen];
				stream.read(val);
				break;
				
			default:
				break;
			}
		} finally {
			stream.close();
		}

		return new String(val, "UTF-8");
	}
	
	public int getSupplementIndex(){
		try {
			return this.getOption(0);
		} catch (Exception e) {
			return -1;
		}
	}

	@Override
	public void readToMemory(MemoryBlock memBlock) {
		if (memBlock instanceof PureContentBlock) {
			try {
				memBlock.setOption(0, this.getOption(0));
				memBlock.setBody(this.getBody(0, this.bodySize), 0);
				memBlock.setBodyVacancy(this.bodyVacancy);
			} catch (Exception e) {
			}
		}
	}

	@Override
	public byte[] getData() throws Exception {
		ByteArrayOutputStream stream = new ByteArrayOutputStream(this.bodySize + 4);
		
		stream.write(ByteConverter.intToByte(this.getOption(0), 4));
		stream.write(this.getBody(0, this.bodySize));
		
		return stream.toByteArray();
	}
}
